package com.jsz.yun.ai.field.service.impl;

import cn.hutool.core.util.ObjUtil;
import com.jsz.yun.ai.field.config.UserConfig;
import com.jsz.yun.ai.field.entity.UserEntity;
import com.jsz.yun.ai.field.enums.ResultCodeEnum;
import com.jsz.yun.ai.field.exception.BusinessException;
import com.jsz.yun.ai.field.repository.UserInfoRepository;
import com.jsz.yun.ai.field.service.UserInfoService;
import com.jsz.yun.ai.field.util.ThreadLocalSetting;
import com.jsz.yun.ai.field.util.TokenUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


/**
 * @author gaoxing
 * @date 2025-03-24 21:30:15
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {


    @Resource
    UserInfoRepository userInfoRepository;

    @Resource
    UserConfig userConfig;

    @Override
    public UserEntity creatUser() {
        // 判断用户是否存在
        UserEntity userEntity = ThreadLocalSetting.USER_INFO_THREADLOCA.get();
        UserEntity user = userInfoRepository.selectUser(userEntity);
        if (ObjUtil.isNotEmpty(user)) {
            throw new BusinessException(ResultCodeEnum.CREATE_USER_FAIL);
        }

        // 判断邀请码是否正确
        if (ObjUtil.isEmpty(userEntity.getPromotionCode()) || !userConfig.getPromotionCode().equals(userEntity.getPromotionCode())) {
            throw new BusinessException(ResultCodeEnum.USER_PROMOTION_CODE_IS_ERROR);
        }
        UserEntity userInfo = userInfoRepository.creatUser(userEntity);
        String token = TokenUtil.generateToken(userInfo.getPhoneNumber());
        userInfo.setToken(token);
        return userInfo;
    }

    @Override
    public UserEntity validateUser() {
        UserEntity userEntity = ThreadLocalSetting.USER_INFO_THREADLOCA.get();
        UserEntity user = userInfoRepository.validateUser(userEntity);
        String token = TokenUtil.generateToken(userEntity.getPhoneNumber());
        user.setToken(token);
        return user;
    }

    @Override
    public UserEntity validateUserDiskSize(long size) {
        UserEntity userEntity = ThreadLocalSetting.USER_FILE_THREADLOCAL.get();
        UserEntity user = userInfoRepository.selectUserById(userEntity.getUserId());
        if (user.getDiskSize() < size){
            throw new BusinessException(ResultCodeEnum.USER_DISK_SIZE_IS_NOT_ENOUGH);
        }
        return user;
    }
}
